package argo.hot100.linklist;

import java.util.ArrayList;
import java.util.List;

public class IsPalindrome {


    public boolean isPalindromeSimp(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int left = 0, right = list.size()-1;
        while (left < right) {
            if (list.get(left) == list.get(right)) {
                left++;
                right--;
            } else {
                return false;
            }
        }
        return true;


    }


    public boolean isPalindrome(ListNode head) {
        if (head.next == null) {
            return true;
        }
        ListNode p0 = null, p1 = head, p2 = head;
        while (p2.next.next != null) {
            p2 = p2.next.next;

            p1 = p1.next;
            p0 = p1;
        }

        ListNode p2h = reverseList(p1.next);

        if (p0 != null) {
            p0.next = null;
        }
        while (head != null && p2h != null && head.val == p2h.val) {
            head = head.next;
            p2h = p2h.next;
        }

        return head == null && p2h == null;

    }


    public ListNode reverseList(ListNode head) {
        if (head.next == null) {
            return head;
        }
        ListNode p1 = null, p2 = head, p3 = null;
        while (p2.next != null) {
            p3 = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = p3;
        }

        return p2;
    }


}
